<?php

namespace App\Models\Admin;

use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Model;
use App\Models\Admin\Grade;
use App\Models\Admin\Good;
use App\Common\ValidateHandler;
use Config;

class Share extends BaseModel
{
    protected $fillable = [
        'id', 'store_id', 'type', 'num',
        'method', 'radio',
        'created_at', 'updated_at'
    ];

    const SHAREINI = [
        'type' => 1,
        'num' => 2,
        'method' => 1,
        'inputRadio' => [
            ['rela' => 1, 'text' => '第一代的比例：', 'radio' => 0],
            ['rela' => 2, 'text' => '第二代的比例：', 'radio' => 0]
        ]
    ];
    // 获取分享经济信息
    public function getShareText($id,$grade)
    {
        $share = $this->where('store_id', $id)->first();
        $share['type_cn'] = $this->typeCn($share['type']);// 奖金类型
        $share['method_cn'] = $this->methodCn($share['method']);// 分享方式
        $share['radio_cn'] = $this->method($share, $grade, 0, 1);// 比例合成的文字
        return $share;
    }
    public function typeCn($type)
    {
        $str = '未知';
        switch ($type) {
            case 1:
                $str = '订单金额';
                break;
            case 2:
                $str = '订单利润';
                break;
            case 3:
                $str = '商品';
                break;
            default:
                # code...
                break;
        }
        return $str;
    }
    public function methodCn($method)
    {
        $str = '未知';
        switch ($method) {
            case 1:
                $str = '关系';
                break;
            case 2:
                $str = '身份';
                break;
            case 3:
                $str = '关系和身份';
                break;
            default:
                # code...
                break;
        }
        return $str;
    }
    // [验证]初始化指定店铺 的 分享经济信息 
    public function analyShare($id, $code = 0)
    {
        $Grade = new Grade;
        $validateGrade = $Grade->validateGrade($id);
        if($validateGrade['code'] !== 20000){
            return $validateGrade;
        }else{
            $storeGarde = $validateGrade['data']['data'];
        }
        if (empty($storeGarde)) {
            return $this->error(['info' => '['.$id.']店铺等级信息不存在!请先完善店铺等级信息!']);
        } else {
            if ($code === 0) {
                return $this->getShare($id);
            }else{
                return $this->success(['data' => $storeGarde, 'info' => '['.$id.']店铺等级信息完整!']);
            }
            
        }
    }

    // 获取指定店铺的初始化数据
    public function getShare($id)
    {
        $shareInfo = [];
        $share = $this->where('store_id', $id)->first();
        if (empty($share)) {
            $shareInfo = self::SHAREINI;
        } else {
            $shareInfo['type'] = $share['type'];
            $shareInfo['num'] = $share['num'];
            $shareInfo['method'] = $share['method'];
            $shareInfo['inputRadio'] = $this->inputRadio($share);// 解析数据库将数据转变为前台可用格式
        }
        return $this->success(['data' => $shareInfo, 'info' => '['.$id.']店铺分享经济信息初始化成功!']);
    }

    // 初始 : 数据库数据 转 前台可识别数据 => 0 解析数据库数据 / 1 解析前台选择变更后传递的数据 
    public function inputRadio($share, $code = 0)
    {
        $inputRadio = [];// 比例信息
        $getGrade = [];// 等级信息
        // if ($share['type'] != 3) {
            if ($share['method'] != 1) {
                $Grade = new Grade;
                $getGrade = $Grade->getGrade($share['store_id']);
            }
            $inputRadio = $this->method($share, $getGrade, $code);
        // }
        return $inputRadio;
    }
    // 终结 : 数据库数据 转 前台可识别数据
    public function method($share, $getGrade, $code = 0, $text_type = 0)
    {
        $inputRadio = [];
        $text = '';
        switch ($share['method']) {
            case 1:
                # 关系...
                $times = $share['num'];
                for ($x = 1; $x <= $times; $x++) {
                    $inputRadio[$x]['rela'] = $x;
                    $inputRadio[$x]['text'] = '第 '.$x.' 代的比例：';
                    $inputRadio[$x]['radio'] = $code === 1 ? 0 : (json_decode($share['radio'])->$x)*100;
                    $text .= $inputRadio[$x]['text'].$inputRadio[$x]['radio'].'%;   ';
                }
                break;
            case 2:
                # 身份...
                $times = count($getGrade);
                for ($x = 0; $x < $times; $x++) {
                    $inputRadio[$x]['grade'] = $x;
                    $inputRadio[$x]['text'] = $getGrade[$x]['title'].' 的比例：';
                    $inputRadio[$x]['radio'] = $code === 1 ? 0 : (json_decode($share['radio'])[$x])*100;
                    $text .= $inputRadio[$x]['text'].$inputRadio[$x]['radio'].'%;   ';
                }
                break;     
            case 3:
                # 关系+身份...
                $times = count($getGrade) * $share['num'];
                $rela = 1;// 代数
                $grade = 0;// 等级标识
                $length = count($getGrade)-1;
                for ($x = 0; $x < $times; $x++) {
                    // 1-0 1-1 2-0 2-1 3-0 3-1
                    if ($grade > $length) {
                        $grade = 0;// 等级重置
                        $rela += 1;//代数+1
                    }
                    $key = $rela.'-'.$grade;
                    $inputRadio[$x]['rela'] = $rela;
                    $inputRadio[$x]['grade'] = $grade;
                    $inputRadio[$x]['text'] = '第 '.$rela.' 代 '.$getGrade[$grade]['title'].' 的比例：';
                    $inputRadio[$x]['radio'] = $code === 1 ? 0 : (json_decode($share['radio'])->$key)*100;
                    $grade += 1;// 等级+1
                    $text .= $inputRadio[$x]['text'].$inputRadio[$x]['radio'].'%;   ';
                }
                break;
            default:
                # code...
                break;
        }
        if ($text_type == 1) {
            $inputRadio['text'] = $text;
        }
        return $inputRadio;
    }

    // 提交分享经济数据
    public function insertAnlayArr($id, $data)
    {
        // 验证 店铺 / 店铺等级信息
        $analyShare = $this->analyShare($id, 1);
        if ($analyShare['code'] != 20000) {
            return $analyShare;
        }
        // 验证 并 得到需要插入的数据格式
        $insertShare = $this->foreachGet($data, $id);
        if ($insertShare['code'] != 20000) {
            return $insertShare;
        }

        //奖励来源为商品时 且 商品表分享经济字段为空 则初始化商品表分享经济字段
        $result = true;
        $arr = [];
        $good = Good::where("store_id", $id)->get()->toArray();
        if(!empty($good)){
            foreach ($good as $key => $value) {
                $share_gold = json_decode($value['share_gold'],true);
                foreach($data['inputRadio'] as $k => $v){
                    if(empty($share_gold) || count($share_gold) != $data['num'] || $share_gold[$v['rela']] != $v['radio']){
                        array_push($arr,$value['id']);
                    }
                }
                
            }
        }
        
        if($data['type'] == 3 && $data['method'] == 1){
            $radio = $insertShare['data']['data']['radio'];
            if(!empty($arr)){
                $result = Good::where("store_id", $id)->whereIn("id",$arr)->update(["share_gold"=>$radio]);
            }
        }
        if(!$result){
            return $this->error(['data' => $radio,'info'=> '['.$id.']店铺商品的分享经济初始化失败!']);
        }
        
        // 验证分享经济数据是否存在 , 并以此决定 插入 或 更新
        $shareGold = $this->shareGold($id);
        if ($shareGold) {
            $back = $this->where('store_id', $id)->update($insertShare['data']['data']);
        } else {
            $back = $this->create($insertShare['data']['data']);
        }
        if (!$back) {
            return $this->error(['data' =>  $insertShare['data']['data'],'info' => '['.$id.']店铺分享经济信息创建失败!']);
        }else{
            return $this->success(['data' =>  $insertShare['data']['data'], 'info' => '['.$id.']店铺分享经济信息创建成功!']);
        }
    }

    // 验证此店铺分享经济是否存在
    public function shareGold($id)
    {
        return $this->where('store_id', $id)->first();
    }

    // 遍历前台数据 形成插入的内容
    public function foreachGet($data, $id)
    {
        $insert = [];
        $res = $this->validate($data);
        if (!$res['res']) {
            return $this->error(['info' => $res['info']]);
        }
        $insert['store_id'] = $id;
        $insert['type'] = $data['type'];
        $insert['num'] = $data['num'];
        $insert['method'] = $data['method'];
        $radio = $this->insertRadio($data);
        $insert['radio'] = $radio ? json_encode($radio) : $radio;// 通过前台数据 得到 数据库所需数据
        return $this->success(['data' =>  $insert, 'info' => '插入数据验证成功!']);
    }
    //店铺会员等级表 字段合法性验证
    private function validate($data)
    {
        $arr = [
            0 => [
                'name' => '金额来源',
                'value' => $data['type'],
                'func' => 'range_status',
                'arr' => Config::get("const.share_type")
            ],
            2 => [
                'name' => '分享级数',
                'value' => $data['num'],
                'func' => 'range_num',
                'min' => 0,
                'max' => 10
            ],
            3 => [
                'name' => '分享方式',
                'value' => $data['method'],
                'func' => 'range_status',
                'arr' => Config::get("const.share_method")
            ]
        ];
        return ValidateHandler::do($arr);
    }
    public function insertRadio($data)
    {
        $radio = [];
        $inputRadio = $data['inputRadio'];
        // if ($data['type'] == 3) {
        //     return '';
        // }
        switch ($data['method']) {
            case 1:
                # 关系...
                foreach ($inputRadio as $key => $val) {
                    $radio[$val['rela']] = $val['radio']/100;
                }
                break;
            case 2:
                # 关系...
                foreach ($inputRadio as $key => $val) {
                    $radio[(string)$val['grade']] = $val['radio']/100;
                }
                break;
            case 3:
                # 关系...
                foreach ($inputRadio as $key => $val) {
                    $keyRadio = $val['rela'].'-'.$val['grade'];
                    $radio[$keyRadio] = $val['radio']/100;
                }
                break;
            default:
                # code...
                break;
        }
        return $radio;
    }
}
